package project.dade.cn.bst.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.AppCompatButton;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.daimajia.androidanimations.library.Techniques;
import com.daimajia.androidanimations.library.YoYo;
import com.kyleduo.switchbutton.SwitchButton;
import com.squareup.okhttp.Request;

import java.util.HashMap;
import java.util.Map;

import butterknife.InjectView;
import project.dade.cn.bst.R;
import project.dade.cn.bst.base.ZJPBaseBarActivity;
import project.dade.cn.bst.manager.ApiConfig;
import project.dade.cn.bst.manager.AppApplication;
import project.dade.cn.bst.model.BaseRequestsModel;
import project.dade.cn.bst.network.FormatRequest;
import project.dade.cn.bst.network.callback.ResultCallback;
import project.dade.cn.bst.network.request.OkHttpRequest;
import project.dade.cn.bst.utils.AppUtil;
import project.dade.cn.bst.utils.LogUtil;
import project.dade.cn.bst.utils.NetRequestUtil;
import project.dade.cn.bst.utils.ToastUtil;
import project.dade.cn.bst.utils.ValidateUtil;

/**
 * Created by vain zhou on 2015/11/2.
 */
public class AddaddressActivity extends ZJPBaseBarActivity implements View.OnClickListener{
    public static int RESULT_CODE = 1201;
    @InjectView(R.id.tv_area)
    EditText tv_eare;
    @InjectView(R.id.universal_toolBarTitle)
    TextView toolBar;
    @InjectView(R.id.addBtn)
    AppCompatButton address;
    @InjectView(R.id.et_name)
    EditText name;
    @InjectView(R.id.et_mobile)
    EditText mobile;
    @InjectView(R.id.default_Gesture)
    SwitchButton defaultGesture;
   private int stat=0;
    private  String tv_name;
    private String tv_phone;
    private String tv_address;
    private String id="";
    private  String edit="";
    private String mark="";

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_address);
        initSetListener();
        initData();
    }
    private void initData() {
        tv_name = getIntent().getStringExtra("name");
        tv_phone= getIntent().getStringExtra("phone");
        tv_address=getIntent().getStringExtra("address");
        id=getIntent().getStringExtra("id");
        edit=getIntent().getStringExtra("edit");
        mark=getIntent().getStringExtra("mark");
        name.setText(tv_name);
        mobile.setText(tv_phone);
        tv_eare.setText(tv_address);
    }

    private void initSetListener() {
        tv_eare.setOnClickListener(this);
        toolBar.setOnClickListener(this);
        address.setOnClickListener(this);
        defaultGesture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                defaultGesture.setChecked(!defaultGesture.isChecked());
                if (defaultGesture.isChecked()) {
                    stat = 1;
                } else {
                    stat = 0;
                }

            }
        });
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            this.finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.universal_toolBarTitle:
                Intent intent = new Intent();
                intent.putExtra("type","2");
                intent.putExtra("mark",mark);
                intent.setClass(AddaddressActivity.this,ChooseAddressActivity.class);
                startActivityForResult(intent,  ChooseAddressActivity.RESULT_CODE);

                break;
            case R.id.addBtn:
                if (isCheckInput()) {
                    if (AppUtil.isNetworkAvailable(AddaddressActivity.this)) {
                        if(edit.equals("1")){
                            requestModiftyRess();
                        }else {
                            requestAddRess();
                        }
                    } else {
                        ToastUtil.showShort(AddaddressActivity.this, R.string.tips_network_error);

                    }
                }
                break;
        }
    }
    private void requestAddRess() {
        HashMap<String,String > hashMap = new HashMap<String,String>();
        hashMap.put("UID", AppApplication.getInstance().getSpUtil().getUserID().toString());
        hashMap.put("MobilePhone", AppApplication.getInstance().getSpUtil().getUSER_mobile());
        hashMap.put("Name", name.getText().toString().trim());
        hashMap.put("Address", tv_eare.getText().toString().trim());
        hashMap.put("Stat",stat+"" );
        hashMap.put("Phone",mobile.getText().toString().trim() );
        Map<String, String> params = new HashMap<String, String>();
        params.put("UID", AppApplication.getInstance().getSpUtil().getUserID().toString());
        params.put("MobilePhone", AppApplication.getInstance().getSpUtil().getUSER_mobile());
        params.put("Name", name.getText().toString().trim());
        params.put("Address", tv_eare.getText().toString().trim());
        params.put("Stat",stat+"" );
        params.put("Phone", mobile.getText().toString().trim());
        params.put("Sign", FormatRequest.main(hashMap));
        new OkHttpRequest.Builder()
                .url(ApiConfig.getHostAddress()+ApiConfig.SERVER_URL.Address).params(params)
                .post(new ResultCallback<String>(){
                    @Override
                    public void onError(Request request, Exception e) {
                        ToastUtil.showShort(AddaddressActivity.this, "网络相应失败请稍后再试");
                    }
                    @Override
                    public void onResponse(String response) {
                        LogUtil.i(TAG, "提交收获地址：" + response);
                        if (TextUtils.isEmpty(NetRequestUtil.requestsError(response, "提交密码"))) {
                            BaseRequestsModel model = JSON.parseObject(response, BaseRequestsModel.class);

                            if (model != null && model.getResult() == 0) {
                                ToastUtil.showShort(AddaddressActivity.this, "提交收获地址成功");
                                if(mark.equals("1")){
                                    Intent mIntentRegInfo = new Intent(AddaddressActivity.this,MyaddressActivity.class);
                                    mIntentRegInfo.putExtra("mark", "1");
                                    startActivity(mIntentRegInfo);
                                    finish();
                                }else if(mark.equals("2")){
                                    Intent mIntentRegInfo = new Intent(AddaddressActivity.this,MyaddressActivity.class);
                                    mIntentRegInfo.putExtra("mark", "2");
                                    startActivity(mIntentRegInfo);
                                    finish();
                                }else {
                                    Intent mIntentRegInfo = new Intent(AddaddressActivity.this,MyaddressActivity.class);
                                    mIntentRegInfo.putExtra("mark", "3");
                                    startActivity(mIntentRegInfo);
                                    finish();
                                }

                            }
                        }else {
                            ToastUtil.showShort(AddaddressActivity.this, NetRequestUtil.requestsError(response, "提交收获地址"));

                        }
                    }

                }) ;

    }
    private void requestModiftyRess() {
       HashMap<String, String> params = new HashMap<String, String>();
        params.put("Id", id);
        params.put("UID", AppApplication.getInstance().getSpUtil().getUserID().toString());
        params.put("MobilePhone", AppApplication.getInstance().getSpUtil().getUSER_mobile());
        params.put("Name", name.getText().toString().trim());
        params.put("Address", tv_eare.getText().toString().trim());
        params.put("Stat",stat+"" );
        params.put("Phone", mobile.getText().toString().trim());
        params.put("Sign", FormatRequest.main(params));
        new OkHttpRequest.Builder()
                .url(ApiConfig.getHostAddress()+ApiConfig.SERVER_URL.Address).params(params)
                .post(new ResultCallback<String>(){
                    @Override
                    public void onError(Request request, Exception e) {

                        ToastUtil.showShort(AddaddressActivity.this, "网络相应失败请稍后再试");
                    }
                    @Override
                    public void onResponse(String response) {
                        LogUtil.i(TAG, "修改地址：" + response);
                        if (TextUtils.isEmpty(NetRequestUtil.requestsError(response, "修改地址"))) {
                            BaseRequestsModel model = JSON.parseObject(response, BaseRequestsModel.class);

                            if (model != null && model.getResult() == 0) {
                                ToastUtil.showShort(AddaddressActivity.this, "修改地址成功");
                                finish();
                            }
                        }else {
                            ToastUtil.showShort(AddaddressActivity.this, NetRequestUtil.requestsError(response, "修改地址"));

                        }
                    }

                }) ;

    }
    private boolean isCheckInput() {
        //姓名不能为空
        if (TextUtils.isEmpty(name.getText().toString().trim())) {
            ToastUtil.showShort(this, R.string.tips_name);
            YoYo.with(Techniques.Shake)
                    .playOn(findViewById(R.id.et_name));
            return false;
        }
        //收获地址
        if (TextUtils.isEmpty(tv_eare.getText().toString().trim())) {
            ToastUtil.showShort(this, R.string.tips_area);
            YoYo.with(Techniques.Shake)
                    .playOn(findViewById(R.id.tv_area));
            return false;
        }
        //验证手机号码
        if (!ValidateUtil.isMobile(mobile.getText().toString().trim())) {
            ToastUtil.showShort(this, R.string.tips_phone_right);
            YoYo.with(Techniques.Shake).playOn(findViewById(R.id.et_mobile));
            return false;
        }

        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode ==ChooseAddressActivity.RESULT_CODE
                && resultCode == ChooseAddressActivity.RESULT_CODE) {
            Bundle mBundle = data.getBundleExtra("tempAddress");
            String street=mBundle.getString("address");
            mark=mBundle.getString("mark");
            tv_eare.setText(street);
        }

    }
            /**
             * 跳转相关页功能
             *
             * @param <T>
     */
    private <T> void redirectToPage(Class<T> class1) {
        startActivity(new Intent(AddaddressActivity.this, class1));

    }

}
